//
//  DemoPageController.m
//  UniverseProject
//
//  Created by king on 2021/6/17.
//  Copyright © 2021 Cloud2209. All rights reserved.
//

#import <UITextView+WZB.h>
#import "CommenAreaView.h"
#import <IQKeyboardManager/IQKeyboardManager.h>
#import "DemoPageControllerCell.h"
#import "DemoPageController.h"

@interface DemoPageController ()<UITableViewDelegate,UITableViewDataSource>

//键盘弹出时,禁止滚动,键盘弹出时,页面会位移14像素
@property (nonatomic, weak)CommenAreaView *areaView;
@property (nonatomic ,weak) UITableView *tableView;
@property (nonatomic ,strong) NSMutableArray *dataArr;
@property (assign,nonatomic) NSInteger pageNo;
@property (nonatomic, assign)NSInteger counter;


/// 记录键盘尺寸
@property (nonatomic, assign)CGFloat keyboardHeight;

@end

@implementation DemoPageController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"pagingScroll";
    
    self.counter = 5;
    self.pageNo = 1;
    NSMutableArray *dataArr = [NSMutableArray array];
    [dataArr addObjectsFromArray:@[@"1",@"2",@"3",@"4",@"5"]];
    self.dataArr = dataArr;
    
    [self setupTab];
    
    [self loadCommonAreaView];
}

/**
 设置表格
 */
- (void)setupTab{
    
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, K_SCREEN_WIDTH,  K_SCREEN_HEIGHT - k_SafeAreaTopHeight) style:UITableViewStylePlain];
    [self.view addSubview:tableView];
    tableView.pagingEnabled = YES;
    tableView.bounces = NO;
    self.tableView = tableView;
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.showsVerticalScrollIndicator = NO;
    self.tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.estimatedRowHeight = 0;
    self.tableView.estimatedSectionHeaderHeight = 0;
    self.tableView.estimatedSectionFooterHeight = 0;
    
    kWeakSelf(self);
    
//    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
//        weakself.pageNo += 1;
//        [weakself getUserMessageList];
//    }];
//
//    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
//        weakself.pageNo = 1;
//        [weakself getUserMessageList];
//    }];
    tableView.ly_emptyView = [LGDIYEmptyView diyNoDataEmptyImageName:@"newjbflszImage" Title:@"暂无数据" content:@""];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyobardShouldHide) name:@"通知DemoPageController收起键盘" object:nil];
    

    
    
    //设置时间间隔（每五秒）
//    dispatch_source_t _timer;
//    NSTimeInterval period = 5.f;
//    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//    _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
//    dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), period * NSEC_PER_SEC, 0);
//
//    // 事件回调
//    dispatch_source_set_event_handler(_timer, ^{
//        dispatch_async(dispatch_get_main_queue(),^{
//
//            NSArray *visiblePaths = [tableView indexPathsForVisibleRows];
//                for (NSIndexPath *indexPath in visiblePaths)
//                {
//                    //获取到的indexpath为屏幕上的cell的indexpath
//                    DemoPageControllerCell *cell = [tableView cellForRowAtIndexPath:indexPath];
//                    [cell showEnterpriseInfo];
//                }
//        });
//    });

    // 开启定时器
//    dispatch_resume(_timer);
    // 关闭定时器
    // dispatch_source_cancel(_timer);
    

    
}



#pragma mark -UITableView代理方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
        return self.dataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    kWeakSelf(self);
    DemoPageControllerCell *cell = [DemoPageControllerCell cellWithTableView:tableView];
    cell.boxView.backgroundColor = RandomColor;
    cell.countLab.text = self.dataArr[indexPath.row];
    cell.model_str = self.dataArr[indexPath.row];
    [cell setCallKeyboard:^{
        //唤醒键盘
        [weakself.areaView.tv becomeFirstResponder];
    }];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return K_SCREEN_HEIGHT - k_SafeAreaTopHeight;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//    Class puchClass = NSClassFromString(@"CommunityQuestionListC");
//    PushVC([puchClass new]);
}


- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSLog(@"didEndDisplayingCell,cell消失了")
//    cell消失的时候取消定时器
    DemoPageControllerCell *tcell = (DemoPageControllerCell *)cell;
    [tcell.crv.timer invalidate];
}


#pragma mark 数据加载 界面刷新
-(void)getUserMessageList
{
    NSMutableDictionary *param = [NSMutableDictionary new];
    param[@"page"] = @(self.pageNo);
    param[@"type"] = @(2);//消息类型：0关注1点赞2收藏
    NSString *url = @"api/user/notification";
 
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
           NSMutableArray *indexPathArray = [NSMutableArray new];
           NSInteger row = self.dataArr.count - 1;
           for (int i = 0; i < 3; i ++) {
               [self.dataArr addObject: [NSString stringWithFormat:@"%d",++self.counter]];
               [indexPathArray addObject:[NSIndexPath indexPathForRow:row+i inSection:0]];
           }
        
           [self.tableView.mj_footer endRefreshingWithCompletionBlock:^{
               [self.tableView insertRowsAtIndexPaths:indexPathArray withRowAnimation:UITableViewRowAnimationNone];
//               [self.tableView reloadRowsAtIndexPaths:indexPathArray withRowAnimation:UITableViewRowAnimationNone];
               [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:row+1 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
           }];
    });
    
}


#pragma mark - 页面生命周期
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
//    [[IQKeyboardManager sharedManager] disableInViewControllerClass:[ViewController class]];
//    不能满足我的需求，因为需要看不到弹起的工具条，但是可以用这个方法：
    
    [[IQKeyboardManager sharedManager] setEnable:NO];
    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
}


- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    [[IQKeyboardManager sharedManager] setEnable:YES];
    [IQKeyboardManager sharedManager].enableAutoToolbar = YES;
    
}




#pragma mark - 滚动事件
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
//    NSLog(@"%f",scrollView.contentOffset.y);
}

#pragma mark - 键盘&通知事件


- (void)dealloc{
   
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    NSLog(@"DemoPageController页面释放")
}


-(void)keyboardWillChangeFrame:(NSNotification*)notification
{
    NSDictionary *userInfo = [notification userInfo];
    NSValue* aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];//更改后的键盘
    
    CGRect keyboardRect = [aValue CGRectValue];
    CGFloat height = keyboardRect.size.height;
    self.keyboardHeight = height;
    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration;
    [animationDurationValue getValue:&animationDuration];
    
//    NSLog(@"键盘位置改变%@ 屏幕高度%f",NSStringFromCGRect(keyboardRect),K_SCREEN_HEIGHT);
    //以下为你要改变的View的Fram
//    _commentArea.y = K_SCREEN_HEIGHT- height - 49;
    
    if (keyboardRect.origin.y == K_SCREEN_HEIGHT) {
        //键盘即将收起
        [UIView animateWithDuration:animationDuration animations:^{
            self.areaView.y = K_SCREEN_HEIGHT;
        }];
    }else{
        //键盘即将打开
        [UIView animateWithDuration:animationDuration animations:^{
            self.areaView.y = keyboardRect.origin.y - k_SafeAreaTopHeight -44;
        } completion:^(BOOL finished) {
            [self.areaView.tv wzb_textViewHeightDidChanged];
        }];
    }
}


- (void)keyobardShouldHide{
    [self.areaView.tv endEditing:YES];
}


#pragma mark - 评论区

- (void)loadCommonAreaView{
    CommenAreaView *areaView = [[CommenAreaView alloc] initWithFrame:CGRectMake(0, K_SCREEN_HEIGHT, K_SCREEN_WIDTH, 44)];
    [self.view addSubview:areaView];
    areaView.backgroundColor = [UIColor yellowColor];
    self.areaView = areaView;
    
    // 避免循环引用
    __weak typeof (areaView) weakAreaView = areaView;
    kWeakSelf(self);
    //这个值是初始一行的高度
    areaView.tv.wzb_minHeight = 34;
    CGFloat padding = areaView.height - areaView.tv.wzb_minHeight;
    [areaView.tv wzb_autoHeightWithMaxHeight:80 textViewHeightDidChanged:^(CGFloat currentTextViewHeight) {
        NSLog(@"currentTextViewHeight---%f",currentTextViewHeight);
//                CGRect frame = weakTextView.frame;
//                frame.size.height = currentTextViewHeight;
                [UIView animateWithDuration:0.2 animations:^{
//                    NSLog(@"currentTextViewHeight---%f",currentTextViewHeight);
                    weakAreaView.y = K_SCREEN_HEIGHT - weakself.keyboardHeight - currentTextViewHeight - k_SafeAreaTopHeight - padding;
                    weakAreaView.height = currentTextViewHeight + padding;
                }];
    }];
    
}




@end
